package com.jelly.web.modules.system.role.service.impl;

import com.jelly.common.constant.Constant;
import com.jelly.common.util.ListUtil;
import com.jelly.common.util.StringUtils;
import com.jelly.common.util.back.FilterChainDefinitionsUtil;
import com.jelly.common.util.back.ShiroUtil;
import com.jelly.common.util.web.BuildTreeUtil;
import com.jelly.common.web.tree.Tree;
import com.jelly.config.shiro.token.TokenUtil;
import com.jelly.web.modules.system.permission.dao.PermissionAndRoleMapper;
import com.jelly.web.modules.system.permission.domain.Permission;
import com.jelly.web.modules.system.permission.domain.PermissionAndRole;
import com.jelly.web.modules.system.permission.domain.PermissionAndRoleExample;
import com.jelly.web.modules.system.permission.service.IPermissionService;
import com.jelly.web.modules.system.role.dao.RoleMapper;
import com.jelly.web.modules.system.role.dao.UserAndRoleMapper;
import com.jelly.web.modules.system.role.domain.Role;
import com.jelly.web.modules.system.role.domain.RoleExample;
import com.jelly.web.modules.system.role.domain.UserAndRole;
import com.jelly.web.modules.system.role.domain.UserAndRoleExample;
import com.jelly.web.modules.system.role.service.IRolePermissionService;
import com.jelly.web.modules.system.role.service.IRoleService;
import com.jelly.web.modules.staff.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建人 ql
 * @创建时间 2018-08-29 17:03
 * @项目名称 jelly
 * @功能描述: 角色接口实现类
 **/
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserAndRoleMapper userAndRoleMapper;

    @Autowired
    private PermissionAndRoleMapper permissionAndRoleMapper;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRolePermissionService rolePermissionService;


    @Override
    public List<Tree<Role>> getTreeRole() {

        List<Role> list = getRole(Constant.SUCCESS);

        if(ListUtil.isNotList(list)){
            List<Tree<Role>> trees = new ArrayList<Tree<Role>>();
            //循环添加tree树结构
            for (Role role : list){

                Tree<Role> tree = new Tree<Role>();

                tree.setId(role.getRoleId());

                tree.setParentId(role.getParentId());

                tree.setText(role.getRoleName());

                trees.add(tree);

            }
            // 默认顶级菜单为０，根据数据库实际情况调整
            Tree<Role> t = BuildTreeUtil.build(trees);

            return t.getChildren();
        }

        return null;

    }
    /**
     * 获取角色下的权限tree
     * @param roleId 角色id
     * @return
     */
    @Override
    public List<Tree<PermissionAndRole>> getTreeRolePermission(String roleId) {

        PermissionAndRoleExample example = new PermissionAndRoleExample();
        example.createCriteria().andRoleIdEqualTo(roleId);

        List<PermissionAndRole> list = permissionAndRoleMapper.selectByExample(example);
        if(ListUtil.isNotList(list)){

            //获取所有正常的权限信息
            List<Permission> permissionList = permissionService.getPermissionList(Constant.SUCCESS);

            if(ListUtil.isNotList(permissionList)){

                //取出当前角色下的权限信息
                List<String> perList = ListUtil.getFieldValues(list,"perId");

                //取出权限下的所有父级权限id
                List<String> parentIdList = ListUtil.getFieldValues(permissionList,"parentId");

                List<Tree<PermissionAndRole>> trees = new ArrayList<Tree<PermissionAndRole>>();
                //循环添加tree树结构
                for (Permission permission : permissionList){

                    Tree<PermissionAndRole> tree = new Tree<PermissionAndRole>();

                    tree.setId(permission.getPerId());

                    tree.setParentId(permission.getParentId());

                    tree.setText(permission.getPerName());
                    //存放节点状态
                    Map<String, Object> state = new HashMap<>();

                    //获取权限id并判断当前角色是否包含此权限
                    String perId = permission.getPerId();

                    if (perList.contains(perId)) {

                        if(parentIdList.contains(perId)){

                            state.put("undetermined",true);

                        }else{

                            state.put("selected", true);

                        }

                    }else{

                        state.put("selected", false);

                    }

                    tree.setState(state);

                    trees.add(tree);

                }

                // 默认顶级菜单为０，根据数据库实际情况调整
                Tree<PermissionAndRole> t = BuildTreeUtil.build(trees);

                return t.getChildren();

            }


        }
        return null;
    }

    /**
     * 获取所有角色
     * @param isState 状态
     * @return
     */
    @Override
    public List<Role> getRole(String isState) {

        RoleExample example = new RoleExample();

        example.createCriteria().andIsStateEqualTo(isState);

        return roleMapper.selectByExample(example);

    }
    /**
     * 获取所有角色
     * @param role 条件
     * @return
     */
    @Override
    public List<Role> getRole(Role role) {

        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();

        if(StringUtils.isNotBlank(role.getRoleName())){
            criteria.andRoleNameEqualTo(role.getRoleName());
        }
        if(StringUtils.isNotBlank(role.getRoleRoute())){
            criteria.andRoleRouteEqualTo(role.getRoleRoute());
        }
        if(StringUtils.isNotBlank(role.getIsState())){
            criteria.andIsStateEqualTo(role.getIsState());
        }

        if(StringUtils.isNotBlank(role.getStartTime()) && StringUtils.isNotBlank(role.getEndTime())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                criteria.andAddDateGreaterThanOrEqualTo(sdf.parse(role.getStartTime()));
                criteria.andAddDateLessThanOrEqualTo(sdf.parse(role.getEndTime()));
            }catch (Exception e){

            }
        }

        return roleMapper.selectByExample(example);
    }
    /**
     * 获取角色详情
     * @param roleId 角色id
     * @return
     */
    @Override
    public Role getRoleId(String roleId) {
        return roleMapper.selectByPrimaryKey(roleId);
    }

    /**
     * 新增角色
     * @param role 条件
     * @return
     */
    @Override
    public boolean addRole(Role role) {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        role.setRoleId(id);
        role.setAddDate(new Date());
        role.setAddId(TokenUtil.getUserId());

        if(ListUtil.isNotList(role.getMenuIds())){
            for (String key : role.getMenuIds()){
                rolePermissionService.addRolePermission(role.getRoleId(),key);
            }
        }

        return roleMapper.insertSelective(role) > 0;
    }

    /**
     * 修改角色
     * @param role 条件
     * @return
     */
    @Override
    public boolean updateRole(Role role) {

        if(StringUtils.isNotBlank(role.getBaseId())){
            role.setRoleId(role.getBaseId());
        }

        if(ListUtil.isNotList(role.getMenuIds())){

            if(rolePermissionService.delectRolePermission(role.getRoleId(),"")){
                for (String key : role.getMenuIds()){
                    rolePermissionService.addRolePermission(role.getRoleId(),key);
                }
            }

        }
        role.setUpdateDate(new Date());
        role.setUpdateId(TokenUtil.getUserId());
        boolean bol = roleMapper.updateByPrimaryKeySelective(role) > 0;
        if(bol){
            UserAndRoleExample example = new UserAndRoleExample();
            example.createCriteria().andRoleIdEqualTo(role.getRoleId());
            List<UserAndRole> list = userAndRoleMapper.selectByExample(example);
            if(ListUtil.isNotList(list)){
                for (UserAndRole userAndRole : list){
                    List<User> userList = userAndRole.getUserList();
                    if(ListUtil.isNotList(userList)){
                        for (User user:userList){
                            ShiroUtil.updateSession(user.getLoginAccount());
                        }
                    }
                }
                //更新拦截信息
                FilterChainDefinitionsUtil.updatePermission();
            }
        }
        return bol;
    }
    /**
     * 删除角色
     * @param roleId 条件
     * @return
     */
    @Override
    public boolean delectRole(String roleId) {
        if(StringUtils.isNotBlank(roleId)){
            if(rolePermissionService.delectRolePermission(roleId,"")){
                if(roleMapper.deleteByPrimaryKey(roleId) > 0){
                    //更新拦截信息
                    FilterChainDefinitionsUtil.updatePermission();
                    return true;
                }

            }
        }
        return false;
    }
}
